<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :before-close="close"
    :visible="dialogFormVisible"
    :title="title"
    width="800px"
    :top="'10vh'"
  >
    <div class="custom-body">
      <div class="custom-ul">
        <el-checkbox-group v-model="checkList">
          <div v-for="item in dataList" :key="item.id">
            <div class="custom-header">{{ item.title }}</div>
            <div v-if="item.childList" class="custom-li-body">
              <el-checkbox v-for="obj in item.childList" :key="obj.id" :label="obj.id">{{ obj.title }}</el-checkbox>
            </div>
          </div>
        </el-checkbox-group>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="close">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSave">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { queryAllFwfl, saveAllServiceFl, queryAllServiceFl } from '@/api/fwfl'

export default {
  name: 'ServerEdit',
  data() {
    return {
      dialogFormVisible: false,
      title: '服务设置',
      service: {},
      loading: false,
      checkList: [],
      dataList: [],
      form: {
        serviceId: null,
        flId: []
      }
    }
  },
  methods: {
    openEntity(data) {
      if (undefined !== data) {
        this.dialogFormVisible = true
        this.service = data
        this.init()
        this.initService(data.id)
      } else {
        this.$message.error('请选择服务！')
      }
    },
    async init() {
      queryAllFwfl().then(res => {
        const { data } = res
        this.dataList = data
      }).catch(() => {
        console.log('初始化数据失败')
      })
    },
    initService(sid) {
      queryAllServiceFl({ sid: sid }).then(res => {
        const { data } = res
        if (data !== null && data.length > 0) {
          this.checkList = data.map(item => {
            return item.fwflId
          })
        } else {
          this.checkList = []
        }
      }).catch(() => {
        console.log('初始化数据失败')
      })
    },
    close() {
      this.dialogFormVisible = false
      this.$emit('fetch-data')
    },
    doSave() {
      this.form.serviceId = this.service.id
      this.form.flId = this.checkList
      saveAllServiceFl(this.form).then(res => {
        this.close()
      }).catch(() => {
        console.log('保存失败！')
      })
    }
  }
}
</script>

<style scoped>
.custom-body {
  width: 100%;
  min-height: 400px;
  padding: 0 20px;
  box-sizing: border-box;
}

.custom-ul {
  width: 100%;
  height: auto;
}

.custom-header {
  position: relative;
  height: 40px;
  line-height: 40px;
  text-align: left;
  text-indent: 20px;
  font-size: 16px;
  font-weight: bolder;
  background-color: #eeeeee;
}

.custom-li-body {
  padding: 10px 0px;
  box-sizing: border-box;
}
</style>
